﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace ReTool
{
    public static partial class ReHandler
    {
        /// <summary>
        /// 开启文件修改监控
        /// </summary>
        public static void BeginMonitor()
        {
            string path = string.Empty;
            if (!string.IsNullOrEmpty(_option.DicPath))
            {
                path = _option.DicPath;
            }
            else if (!string.IsNullOrEmpty(_option.FilePath))
            {
                path = _option.FilePath;
            }
            else
            {
                Error("无有效监控路径");
            }
            Info("文件监控开启");

            using var watcher = new FileSystemWatcher(@path);

            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;

            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;
            watcher.Error += OnError;

            watcher.Filter = "";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;

            while (true) { Thread.Sleep(TimeSpan.FromHours(1)); }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            Info($"Changed: {e.FullPath}");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Info($"Created: {e.FullPath}");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e) =>
            Warn($"Deleted: {e.FullPath}");

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Info($"Renamed: \r\n\t  Old: {e.OldFullPath} \r\n\t  New: {e.FullPath} \r\n ");
        }

        private static void OnError(object sender, ErrorEventArgs e) =>
            Error(e.GetException().Message, true);


    }
}
